package sk.stuba.fiit.repka.dp.rating.gui;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

import org.apache.log4j.Logger;

import sk.stuba.fiit.repka.dp.db.DBRatingManipulator;
import sk.stuba.fiit.repka.dp.db.DataManipulator;
import sk.stuba.fiit.repka.dp.db.DatabaseController;
import sk.stuba.fiit.repka.dp.owl.gui.MainPanel;

public class RatingPanel extends JPanel implements ActionListener{
	private static Logger logger = Logger.getLogger(RatingPanel.class);
	
	private static final String RATING_INFORMATIONS_LEFT = "Insert RATING of RECOMMENDATIONS which were offered to you " +
			"during ONTOLOGY creation. In your rating consider RESULT (composit web service) which you got.";
	
	private static final String RATING_INFORMATIONS_RIGHT = "Insert RATING of actually used ONTOLOGY. " +
			"In your rating consider RESULT (composit web service) which you got.";
	
	private static final String EXPLANATIONS = "\n('5' is the best - ONTOLOGY was very useful and you got ESTIMATED result)";
	
	private static final String[] composers = {"  OWLS - XPlan 2.0  "};
	
	private RatingPropertiesPanel ratingPropertiesPanelRight;
	private RatingPropertiesPanel ratingPropertiesPanelLeft;
	
	private MainPanel parent;
	
	/**
	 * Create the panel.
	 */
	public RatingPanel(MainPanel parent) {
		this.parent = parent;
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0, 0};
		gridBagLayout.rowHeights = new int[]{369, 43, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);
		
		ratingPropertiesPanelLeft = new RatingPropertiesPanel();
		GridBagConstraints gbc_ratingPropertiesPanelLeft = new GridBagConstraints();
		gbc_ratingPropertiesPanelLeft.insets = new Insets(0, 0, 5, 5);
		gbc_ratingPropertiesPanelLeft.fill = GridBagConstraints.BOTH;
		gbc_ratingPropertiesPanelLeft.gridx = 0;
		gbc_ratingPropertiesPanelLeft.gridy = 0;
		add(ratingPropertiesPanelLeft, gbc_ratingPropertiesPanelLeft);
		JTextPane txtPaneLeft = ratingPropertiesPanelLeft.getRatingInformationsTP();
		this.setTextPaneStyle(txtPaneLeft, RATING_INFORMATIONS_LEFT);
		
		ratingPropertiesPanelRight = new RatingPropertiesPanel();
		GridBagConstraints gbc_ratingPropertiesPanelRight = new GridBagConstraints();
		gbc_ratingPropertiesPanelRight.insets = new Insets(0, 0, 5, 0);
		gbc_ratingPropertiesPanelRight.fill = GridBagConstraints.BOTH;
		gbc_ratingPropertiesPanelRight.gridx = 1;
		gbc_ratingPropertiesPanelRight.gridy = 0;
		add(ratingPropertiesPanelRight, gbc_ratingPropertiesPanelRight);
		JTextPane txtPaneRight = ratingPropertiesPanelRight.getRatingInformationsTP();
		this.setTextPaneStyle(txtPaneRight, RATING_INFORMATIONS_RIGHT);
		
		JPanel composersPanel = new JPanel();
		composersPanel.setBorder(new TitledBorder(null, "Select Composer for which you are inserting rating", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GridBagConstraints gbc_composersPanel = new GridBagConstraints();
		gbc_composersPanel.gridwidth = 2;
		gbc_composersPanel.insets = new Insets(0, 0, 5, 5);
		gbc_composersPanel.fill = GridBagConstraints.BOTH;
		gbc_composersPanel.gridx = 0;
		gbc_composersPanel.gridy = 1;
		add(composersPanel, gbc_composersPanel);
		GridBagLayout gbl_composersPanel = new GridBagLayout();
		gbl_composersPanel.columnWidths = new int[]{0, 0};
		gbl_composersPanel.rowHeights = new int[]{0, 0};
		gbl_composersPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gbl_composersPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
		composersPanel.setLayout(gbl_composersPanel);
		
		JComboBox composersCBox = new JComboBox(composers);
		GridBagConstraints gbc_composersCBox = new GridBagConstraints();
		gbc_composersCBox.insets = new Insets(0, 0, 5, 0);
		gbc_composersCBox.gridx = 0;
		gbc_composersCBox.gridy = 0;
		composersPanel.add(composersCBox, gbc_composersCBox);
		
		JPanel buttonPanel = new JPanel();
		GridBagConstraints gbc_buttonPanel = new GridBagConstraints();
		gbc_buttonPanel.gridwidth = 2;
		gbc_buttonPanel.fill = GridBagConstraints.BOTH;
		gbc_buttonPanel.gridx = 0;
		gbc_buttonPanel.gridy = 2;
		add(buttonPanel, gbc_buttonPanel);
		GridBagLayout gbl_buttonPanel = new GridBagLayout();
		gbl_buttonPanel.columnWidths = new int[]{0, 0};
		gbl_buttonPanel.rowHeights = new int[]{0, 0};
		gbl_buttonPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gbl_buttonPanel.rowWeights = new double[]{1.0, Double.MIN_VALUE};
		buttonPanel.setLayout(gbl_buttonPanel);
		
		JButton btnSendRating = new JButton("Send Rating");
		btnSendRating.addActionListener(this);
		GridBagConstraints gbc_btnSendRating = new GridBagConstraints();
		gbc_btnSendRating.gridx = 0;
		gbc_btnSendRating.gridy = 0;
		buttonPanel.add(btnSendRating, gbc_btnSendRating);

	}
	
	private void setTextPaneStyle(JTextPane txtPane, String text) {
		StyledDocument doc = txtPane.getStyledDocument();
		Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
		Style regular = doc.addStyle("regular", def);
	    StyleConstants.setFontFamily(def, "SansSerif");
	    StyleConstants.setItalic(regular, true);
	    StyleConstants.setForeground(regular, Color.red);
	    StyleConstants.setFontSize(regular, 16);
	    Style explanation = doc.addStyle("explanation", regular);
	    StyleConstants.setFontSize(explanation, 12);
	    try {
			doc.insertString(doc.getLength(), text, doc.getStyle("regular"));
			doc.insertString(doc.getLength(), EXPLANATIONS, doc.getStyle("explanation"));
		} catch (BadLocationException e) {
			System.out.println("Couldn't insert initial text into text pane.");
		}
	}
	
	//return selected radio button from group of radio buttons
	private JRadioButton getSelection(ButtonGroup group) {
	    for (Enumeration e=group.getElements(); e.hasMoreElements(); ) {
	        JRadioButton b = (JRadioButton)e.nextElement();
	        if (b.getModel() == group.getSelection()) {
	            return b;
	        }
	    }
	    return null;
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		JRadioButton leftRB = getSelection(this.ratingPropertiesPanelLeft.getRatingButtonGroup());
		JRadioButton rightRB = getSelection(this.ratingPropertiesPanelRight.getRatingButtonGroup());
		int ratingRecommendations = Integer.parseInt(leftRB.getText());
		int ratingOnotology = Integer.parseInt(rightRB.getText());
		DatabaseController dbControl = this.parent.getMainWindow().getDBController();
		DataManipulator manipulator = new DBRatingManipulator(dbControl, this.parent.getMainWindow().getOntoName(), ratingOnotology, ratingRecommendations);
		try {
			manipulator.insert();
			manipulator.update(this.parent.getUsedRecommendations());
			logger.debug("Rating was stored to DB.");
		} catch (SQLException e) {
			logger.error("Error during storig rating to DB");
			try {
            	logger.error("Transaction is being rolled back");
            	dbControl.getCon().rollback();
            	dbControl.getCon().setAutoCommit(true);
            } catch(SQLException excep) {
            	logger.error("Error during rolled back");
            }
			e.printStackTrace();
		}
	}

}
